from src.modules.knowbase.repository.dao.file_dao import FileDao
from fastapi import UploadFile, File
import os
from core.config import settings
import shutil

from src.modules.knowbase.services.Interface.file_interface import IFileInterface



class FileService(IFileInterface):

    async def get_file_list(self, user_id: str = None,
                            kb_id: str = None,
                            keyword: str = None,
                            page: int = 1, page_size: int = 10
                            ) -> dict:
        return await FileDao.get_file_list(
            user_id=user_id, kb_id=kb_id, keyword=keyword,
            page=page, page_size=page_size
        )


    async def delete_by_file_id(self,file_id: str) -> bool:
        return await FileDao.delete_by_file_id(file_id)

    async def upload_file(self,knowbase_name: str, kb_id: str, file: UploadFile = File(...)):
        # from ..containers import Container
        # container = Container()
        # kb_service = container.kb_service()
        # result = await kb_service.get_kb_list()
        # print(result)

        file_name_without_ext = os.path.splitext(file.filename)[0]
        file_dir = os.path.join(settings.MEDIA_ROOT, knowbase_name, file_name_without_ext)
        file_path = os.path.join(settings.MEDIA_ROOT, knowbase_name, file_name_without_ext, file.filename)
        file_type = file.filename.split(".")[-1]
        os.makedirs(file_dir, exist_ok=True)
        print(file_path)
        with open(file_path, "wb") as f:
            shutil.copyfileobj(file.file, f)
        # return success(message="文件上传成功",data=db_file)
        return await FileDao.upload_file(file_name_without_ext, file_path, kb_id, file_type)

